%%%-------------------------------------------------------------------
%%% File	: sms_demo.erl
%%% Author	: Anton Fedorov <datacompboy@call2ru.com>
%%% Original Author	: Erik Reitsma <Erik.Reitsma@etm.ericsson.se>
%%% Description : Example for erlsoap.
%%%-------------------------------------------------------------------
%%% Created : by Erik Reitsma <elnerei@tina29.etm.ericsson.se>
%%% Updated : 18 sep 2006 by Anton Fedorov <datacompboy@call2ru.com>
%%%-------------------------------------------------------------------


-module(sms_demo).
-vsn("0.4").

-include("../demo/sms_demo.hrl").

-compile(export_all).

start() ->
	mod_soap:start(),
	soap_registry_server:add_xsd("/soap/sms", "sms_demo.xsd"),
	soap_registry_server:add_xsd("http://localhost:8888/soap/sms", "sms_demo.xsd"),
	mod_soap:add_callback("/soap/sms", fun(I,X) -> soap_sms(I,X) end).

soap_sms(I,X) ->
	io:format("soap_sms(~p)~n",[{I,X}]),
	soap_sms_switch(X).

soap_sms_switch(X) when is_record(X,'p:SendSMS') ->
	soap_send_sms(X);

soap_sms_switch(X) when is_record(X,'p:GetStatus') ->
	soap_get_status(X).

soap_send_sms(X) ->
	io:format("Called send_soap_sms with (~p)~n",[X]),
	DestAddressSet = X#'p:SendSMS'.'destinationAddressSet',
	Sender = X#'p:SendSMS'.senderName,
	Billing = X#'p:SendSMS'.charging,
	Message = X#'p:SendSMS'.message,
	Numbers = lists:map(
				fun(E) -> E#'p:EndUserIdentifier'.number end,
				DestAddressSet#'p:SendSMS/destinationAddressSet'.'EndUserIdentifier'
			),
	ID = send_sms(Numbers,Message,Sender,Billing),
	{ok,#'p:resultType'{result=ID}}.

soap_get_status(#'p:GetStatus'{anyAttribs=_, 'RequestID'=ID}) ->
	.io:format("Called get_status for ID = ~p~n",[ID]),
	Status1 = #'p:GetStatus_Response/Status'{'Destination'=#'p:EndUserIdentifier'{number="tel:123"}, 
											 'Status'="Delivered"},
	Status2 = #'p:GetStatus_Response/Status'{'Destination'=#'p:EndUserIdentifier'{number="tel:124"}, 
											 'Status'="MessageWaiting"},
	{ok,#'p:GetStatus_Response'{'Status'=[Status1,Status2]}}.

get_status_local(RequestID) ->
	soapclient:invoke("http://localhost:8888/soap/sms",
			   		  "GetStatus",
					  #'p:GetStatus'{'RequestID'=RequestID}).

send_sms_local(Destination) ->
	send_sms_local_multi([Destination]).

send_sms_local_multi(Destinations) ->
	soapclient:invoke("http://localhost:8888/soap/sms",
			   		  "SendSMS",
					  #'p:SendSMS'{
						'destinationAddressSet'=
							#'p:SendSMS/destinationAddressSet'{
								'EndUserIdentifier'=[#'p:EndUserIdentifier'{number=N} || N <- Destinations]
							},
						'senderName' = "tel:1234",
						'charging' = "no bill",
						'message' = "hello all"
					  }).

send_sms(Numbers,Message,_Sender,_Billing) ->
	.io:format("Should send SMS with message ~p to numbers ~p~n",[Message,Numbers]),
	erlang:ref_to_list(make_ref()).
